package org.nobject.common.swing.g;

import java.awt.Component;
import java.awt.Container;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;

/**
 * 可拖拽监听器
 *
 * @author bianrongjun
 * @version 1.0
 */
public class GDragListener implements MouseMotionListener{
	
	/**
	 * x
	 */
	private int x=-1;
	
	/**
	 * y
	 */
	private int y=-1;
	
	Point mp=null;
	
    /* (non-Javadoc)
     * @see java.awt.event.MouseMotionListener#mouseDragged(java.awt.event.MouseEvent)
     */
    public void mouseDragged(MouseEvent e) {
    	Component component=(Component) e.getSource();
    	
    	if(mp==null){
    		mp=component.getMousePosition();
    		x=mp.x;y=mp.y;
    	}
    	
    	
    	//1.保存拖拽触发时第一次的${鼠标相对组件的坐标}
//    	if(mp!=null){
//    		System.out.println(x+":"+y);
//    	}
    	
    	//2.计算坐标。组件新坐标=${鼠标绝对屏幕的坐标}-${父容器绝对屏幕的坐标}-${鼠标相对组件的坐标}
    	Container container=component.getParent();
    	Point screenMoursePoint=MouseInfo.getPointerInfo().getLocation();
    	Point screenContainerPoint= container.getLocationOnScreen();
    	Point p=new Point(screenMoursePoint.x-screenContainerPoint.x-x,screenMoursePoint.y-screenContainerPoint.y-y);
    	
    	//3.设置坐标
    	((Component)e.getSource()).setLocation(p);
    }   

	/* (non-Javadoc)
	 * @see java.awt.event.MouseMotionListener#mouseMoved(java.awt.event.MouseEvent)
	 */
	public void mouseMoved(MouseEvent e) {}
	
	/** 清理  */
	public void end(){
		this.mp=null;
	}
}